{extend name="public/base"}

{block name="title"}
{$data.repair_name}
{/block}

{block name="style"}
{css href="/static/wechat/css/index.css" /}
{css href="/static/wechat/popo/css/index_map.css" /}
<style type="text/css">
    .amap-copyright,.amap-logo{top:200%;}
    #container .amap-marker .amap-icon img{width:auto;height:auto;}
    .weui-popup__overlay{opacity:1;}
    .weui-dialog__btn{color:#0bb20c;font-size:0.8rem;}
    .weui-dialog, .weui-toast{box-shadow:0 0 3px 0 #000;}
    .msg_panel,.msg_success{position:fixed;top:0px;left:100%;width:100%;height:100%;background:#fff;overflow:auto;}
    #inPanel{background-color:white;width:88%;max-height:88%;margin:0 auto;overflow-y:auto;}
    .order_marker{display:block;width:40px;height:40px;overflow:hidden;margin:10px 0 0 -12px;}
    .order_marker img{display:block;margin:4px auto;width:32px;height:32px;border-radius:50%;box-shadow:0 0 4px 0 #666;}
    .order_marker_on{width:50px;height:50px;margin:5px 0 0 -15px;}
    .order_marker_on img{width:42px;height:42px;box-shadow:0 0 4px 0 #F20;}
    .map_b_bd1{border:1px solid #ccc;border-radius:5px;}
</style>
{/block}

{block name="body"}
<div class="pageControl index2">
    <div class="nav">
        <div class="msui_navTop">
            <a class="msui_navTop-back" href="/wechat/r_store/"><i class="micon-home"></i></a>
            <h1 class="msui_navTop-title">{$data.repair_name}</h1>
            <a class="msui_navTop-icon" href="/wechat/w_message/">
                <i class="micon-message2"></i>
                <span class="weui-badge weui-badge_dot"></span>
            </a>
        </div>
    </div>
    <div id="map" class="weui-cell__bd" style="bottom:0rem;/*4.5*/">
        <div id="container" tabindex="0" style="height: 100%;"></div>
        <p class="map_b map_home" style="left:auto;bottom:10px;right:10px;">
            <span class="map_b_bd1">

            </span>
        </p>

    </div>
    <a class="msui_table msui_tableCom" style="display:none"　href="javascript:;">
        <!--<span class="msui_tabCell-img msui_tableImg-circle" href="homePage.html">-->
        <!--<img src="/static/wechat/images/2.jpg">-->
        <!--</span>-->
        <!--<div class="msui_tabCell-content">-->
        <!--<p class="fs085 cl-3333">[维修]轮胎破了</p>-->
        <!--<p class="fs075 cl-6666">思明区前埔东路588号</p>-->
        <!--<div>-->
        <!--<span class="weui-badge weui-badge_bd">距离约 284m</span>-->
        <!--<p class="msui_date" style="font-size:0.6rem;display: inline-block;">-->
        <!--<span class="cl-9999">12月20日</span>-->
        <!--<span class="cl-9999"> 20:16:56</span>-->
        <!--</p>-->
        <!--</div>-->
        <!--</div>-->
        <!--<span class="msui_tabCell-button">-->
        <!--<i class="micon-in"></i>-->
        <!--</span>-->
    </a>
</div>

<div id="loadingToast" style="display:none;">
    <div class="weui-mask_transparent"></div>
    <div class="weui-toast">
        <i class="weui-loading weui-icon_toast"></i>
        <p class="weui-toast__content">数据加载中...</p>
    </div>
</div>
<div id="iosDialog2" class="js_dialog" style="display:none;">
    <div class="weui-mask_transparent"></div>
    <div class="weui-dialog">
        <div class="weui-dialog__bd">弹窗内容，告知当前状态、信息和解决方法，描述文字尽量控制在三行内</div>
        <div class="weui-dialog__ft">
            <a href="javascript:$('#iosDialog2').hide();" class="weui-dialog__btn weui-dialog__btn_primary">知道了</a>
        </div>
    </div>
</div>
<div class="page msg_panel js_show">
    <div class="weui-msg">
        <div class="weui-msg__text-area">
            <div id="inPanel"></div>
        </div>
        <div class="weui-msg__opr-area">
            <p class="weui-btn-area">
                <a href="javascript:;" onclick="$('.msg_panel').animate({'left':'100%'},200)" class="weui-btn weui-btn_primary">确定</a>
                <!--<a href="javascript:history.back();" class="weui-btn weui-btn_default">辅助操作</a>-->
            </p>
        </div>
    </div>
</div>

{/block}
{block name="javascript"}


<script type="text/javascript" src="http://webapi.amap.com/maps?v=1.3&key=9a8d0d7e358d9d80f7f61a1989ba35a0"></script>
<script>
    window.my = new Object();//存放用户的定位信息
    window.in = new Array();//存放所有商户的定位信息
    //window.in_id = 0;//存放选定商户的定位信息(20170204不能指定,要抢)
    window.in_type = 0;//0:维修,1:拖车,2:保养,3:购车,4:保险
    var mapObj,geolocation,dragTime;

    $(function () {

        $('.map_home').click(function(){
            var tmpUrl = '{:url("index")}';
            window.location.href = tmpUrl;
        });


        //初始化地图
        mapObj = new AMap.Map('container',{
            resizeEnable: true,
            zoom: 15
            //zoomEnable: false,	//禁止放大缩小
            //dragEnable: false,	//禁止拖动
        });

        //开始拖拽地图时
        mapObj.on("dragstart", function(){
            window.clearTimeout(dragTime);
        });
        //拖拽地图过程中
        mapObj.on("dragging", function(){
            //window.clearTimeout(dragTime);

        });
        //停止拖拽地图时
        mapObj.on("dragend", function(){
            dragTime = setTimeout(function() {
                var tmp = mapObj.getCenter();console.log(tmp);
                if(
                        (window.my.position.lng - tmp.lng)<-0.008
                        || (window.my.position.lng - tmp.lng)>0.008
                        || (window.my.position.lat - tmp.lat)<-0.01
                        || (window.my.position.lat - tmp.lat)>0.01
                ){
                    getData(window.in_type,tmp.lng,tmp.lat);
                }
            },888);
        });


        $('#loadingToast').fadeIn();
        //监控用户位置
        mapObj.plugin('AMap.Geolocation', function () {
            geolocation = new AMap.Geolocation({
                enableHighAccuracy: true,//是否使用高精度定位，默认:true
                timeout: 30000,          //超过30秒后停止定位，默认：无穷大
                maximumAge: 0,           //定位结果缓存0毫秒，默认：0
                convert: true,           //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
                showButton: true,        //显示定位按钮，默认：true
                buttonPosition: 'LB',    //定位按钮停靠位置，默认：'LB'，左下角
                buttonOffset: new AMap.Pixel(10,10),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                showMarker: true,        //定位成功后在定位到的位置显示点标记，默认：true
                showCircle: false,        //定位成功后用圆圈表示定位精度范围，默认：true
                panToLocation: true,     //定位成功后将定位到的位置作为地图中心点，默认：true
                zoomToAccuracy:true,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                extensions:'base'
            });
            //markerOptions: window.my_dingdan,
            mapObj.addControl(geolocation);//开始监控
            AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息//onComplete
            AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息
            $(".amap-geo").trigger("click");
        });



    });

    //点单标记被点击
    function order_marker_click(id){

        $(".order_marker").removeClass("order_marker_on");
        $("#order_id_"+id).addClass("order_marker_on");
        $("#map").animate({"bottom":"4.5rem"});
        $(".msui_tableCom").fadeIn();
        $(".msui_tableCom").attr( 'href','{:url("order_info")}?id='+window.in[id].order_id );
        var tmpData = window.in[id].data;
        var tmpData_headimgurl = tmpData.headimgurl.indexOf("://")!=-1?tmpData.headimgurl:SCOPE.image_host_url+tmpData.headimgurl;
        if( !tmpData.headimgurl ){
            tmpData_headimgurl = "/static/wechat/images/tui_03.jpg";
        }
        var tmpHtml = '<span class="msui_tabCell-img msui_tableImg-circle"><img src="'+tmpData_headimgurl+'" ></span>' +
                '<div class="msui_tabCell-content">' +
                '<p class="fs085 cl-3333">['+tmpData.item_name+']'+tmpData.msg+'</p>' +
                '<p class="fs075 cl-6666">'+tmpData.address+'</p>' +
                '<div>' +
                '<span class="weui-badge weui-badge_bd">距离约 '+getFlatternDistance(window.my.position.lat,window.my.position.lng,tmpData.lat,tmpData.lon).toFixed(0)+'m</span>' +
                '<p class="msui_date" style="font-size:0.6rem;display: inline-block;">' +
                '<span class="cl-9999">'+php_date("m月d日",tmpData.add_time)+'</span>' +
                '<span class="cl-9999">'+php_date("H:i:s",tmpData.add_time)+'</span>' +
                '</p>' +
                '</div>' +
                '</div>' +
                '<span class="msui_tabCell-button"><i class="micon-in"></i></span>';
        $(".msui_tableCom").html(tmpHtml);

    }

    //处理定位信息
    function onComplete(data){
        $('#loadingToast').fadeOut();
        if(data.info=="SUCCESS"){
            window.my = data;
            getData(window.in_type,window.my.position.lng, window.my.position.lat);
        }else{
            alert("没有成功获取到您的位置<br>请重新访问...<br>(" + data.message + ")");
        }
    }
    //处理定位出错信息
    function onError(e){
        $('#loadingToast').fadeOut();
        alert("无法获取您的位置<br>请重新访问...<br>(" + e.message + ")");

        /*微信开发工具测试数据*/
        var testObj = {"type":"complete","info":"SUCCESS","status":1,"l3":"jsonp_464548_","position":{"L":28.20703,"I":112.87022000000002,"lng":112.87022,"lat":28.20703},"message":"Get ipLocation success.Get address success.","location_type":"ip","accuracy":null,"isConverted":true,"addressComponent":{"citycode":"0731","adcode":"430104","businessAreas":[{"name":"麓谷","id":"430104","location":{"L":28.21402974876848,"I":112.88941027093597,"lng":112.88941,"lat":28.21403}}],"neighborhoodType":"","neighborhood":"","building":"","buildingType":"","street":"麓松路","streetNumber":"51号","province":"湖南省","city":"长沙市","district":"岳麓区","township":"麓谷街道"},"formattedAddress":"湖南省长沙市岳麓区麓谷街道延农创业大厦延农5期","roads":[],"crosses":[],"pois":[]};
        onComplete(testObj);

    }

    //清除地图上的标记
    function clearData(){
        for(var x in window.in){
            if(window.in[x]){
                window.in[x].setMap(null);
                window.in[x] = undefined;
            }
        }
    }

    //在地图上标记
    function showData(d){

        for(i=0;i<d.length;i++){
            var tmpID = d[i].id;
            var tmpImg;
            if( typeof(window.in[tmpID])!="object" ){
                tmpImg = d[i].headimgurl.indexOf("://")!=-1?d[i].headimgurl:SCOPE.image_host_url+d[i].headimgurl;
                if( !d[i].headimgurl ){
                    tmpImg = "/static/wechat/images/tui_03.jpg";
                }
                window.in[tmpID] = new AMap.Marker({
                    icon: "http://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
                    position: [d[i].lon,d[i].lat]
                });
                window.in[tmpID].setMap(mapObj);
                var tmpHtml = '<a class="order_marker" id="order_id_'+tmpID+'" href="javascript:;"><img src="'+tmpImg+'" /></a>';
                window.in[tmpID].setContent(tmpHtml);
                window.in[tmpID].data = d[i];
                window.in[tmpID].order_id = tmpID;
                AMap.event.addListener(window.in[tmpID], 'click', function() {
                    order_marker_click(this.order_id);
                });
                //window.in[tmpID].on('click', clickData);
            }

        }

    }


    //获取订单数据
    function getData(type,lng,lat){

        //获取商家类型
        window.in_type = type;

        //设为中心点
        mapObj.setCenter([lng,lat]);

        $('#loadingToast').fadeIn();
        $.ajax({
            type:"get",
            cache:false,
            dataType:"json",
            url:"{:url('get_orders_map')}?type="+window.in_type+"&lng="+lng+"&lat="+lat+"&zoom="+mapObj.getZoom(),
            error:function(s){
                $('#loadingToast').fadeOut();
                alert('网络异常');
            },
            success:function(d){
                $('#loadingToast').fadeOut();
                if(d.code!=200){
                    alert(d.msg);
                }else{
                    showData(d.data);
                }
            }
        });
    }

    //改写原生的对话框
    function sAlert(s){
        $('#iosDialog2').show();
        $('#iosDialog2 .weui-dialog__bd').html(s);
    }
    window.alert = function(s){sAlert(s);}






    //单位M
    var EARTH_RADIUS = 6378137.0;
    var PI = Math.PI;
    function getRad(d){
        return d*PI/180.0;
    }
    function getFlatternDistance(lat1,lng1,lat2,lng2){
        var f = getRad((lat1 + lat2)/2);
        var g = getRad((lat1 - lat2)/2);
        var l = getRad((lng1 - lng2)/2);

        var sg = Math.sin(g);
        var sl = Math.sin(l);
        var sf = Math.sin(f);

        var s,c,w,r,d,h1,h2;
        var a = EARTH_RADIUS;
        var fl = 1/298.257;

        sg = sg*sg;
        sl = sl*sl;
        sf = sf*sf;

        s = sg*(1-sl) + (1-sf)*sl;
        c = (1-sg)*(1-sl) + sf*sl;

        w = Math.atan(Math.sqrt(s/c));
        r = Math.sqrt(s*c)/w;
        d = 2*w*a;
        h1 = (3*r -1)/2/c;
        h2 = (3*r +1)/2/s;

        var tmpReturn = d*(1 + fl*(h1*sf*(1-sg) - h2*(1-sf)*sg));
        return (tmpReturn?tmpReturn:0);
    }


    // 和PHP一样的时间戳格式化函数
    // @param  {string} format    格式
    // @param  {int}    timestamp 要格式化的时间 默认为当前时间
    // @return {string}           格式化的时间字符串
    function php_date ( format, timestamp ) {
        var a, jsdate=((timestamp) ? new Date(timestamp*1000) : new Date());
        var pad = function(n, c){
            if( (n = n + "").length < c ) {
                return new Array(++c - n.length).join("0") + n;
            } else {
                return n;
            }
        };
        var txt_weekdays = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"];
        var txt_ordin = {1:"st",2:"nd",3:"rd",21:"st",22:"nd",23:"rd",31:"st"};
        var txt_months = ["", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
        var f = {
            // Day
            d: function(){
                return pad(f.j(), 2);
            },
            D: function(){
                t = f.l(); return t.substr(0,3);
            },
            j: function(){
                return jsdate.getDate();
            },
            l: function(){
                return txt_weekdays[f.w()];
            },
            N: function(){
                return f.w() + 1;
            },
            S: function(){
                return txt_ordin[f.j()] ? txt_ordin[f.j()] : 'th';
            },
            w: function(){
                return jsdate.getDay();
            },
            z: function(){
                return (jsdate - new Date(jsdate.getFullYear() + "/1/1")) / 864e5 >> 0;
            },
            // Week
            W: function(){
                var a = f.z(), b = 364 + f.L() - a;
                var nd2, nd = (new Date(jsdate.getFullYear() + "/1/1").getDay() || 7) - 1;
                if(b <= 2 && ((jsdate.getDay() || 7) - 1) <= 2 - b){
                    return 1;
                } else{
                    if(a <= 2 && nd >= 4 && a >= (6 - nd)){
                        nd2 = new Date(jsdate.getFullYear() - 1 + "/12/31");
                        return date("W", Math.round(nd2.getTime()/1000));
                    } else{
                        return (1 + (nd <= 3 ? ((a + nd) / 7) : (a - (7 - nd)) / 7) >> 0);
                    }
                }
            },
            // Month
            F: function(){
                return txt_months[f.n()];
            },
            m: function(){
                return pad(f.n(), 2);
            },
            M: function(){
                t = f.F(); return t.substr(0,3);
            },
            n: function(){
                return jsdate.getMonth() + 1;
            },
            t: function(){
                var n;
                if( (n = jsdate.getMonth() + 1) == 2 ){
                    return 28 + f.L();
                } else{
                    if( n & 1 && n < 8 || !(n & 1) && n > 7 ){
                        return 31;
                    } else{
                        return 30;
                    }
                }
            },
            // Year
            L: function(){
                var y = f.Y();
                return (!(y & 3) && (y % 1e2 || !(y % 4e2))) ? 1 : 0;
            },
            //o not supported yet
            Y: function(){
                return jsdate.getFullYear();
            },
            y: function(){
                return (jsdate.getFullYear() + "").slice(2);
            },
            // Time
            a: function(){
                return jsdate.getHours() > 11 ? "pm" : "am";
            },
            A: function(){
                return f.a().toUpperCase();
            },
            B: function(){
                // peter paul koch:
                var off = (jsdate.getTimezoneOffset() + 60)*60;
                var theSeconds = (jsdate.getHours() * 3600) +
                        (jsdate.getMinutes() * 60) +
                        jsdate.getSeconds() + off;
                var beat = Math.floor(theSeconds/86.4);
                if (beat > 1000) beat -= 1000;
                if (beat < 0) beat += 1000;
                if ((String(beat)).length == 1) beat = "00"+beat;
                if ((String(beat)).length == 2) beat = "0"+beat;
                return beat;
            },
            g: function(){
                return jsdate.getHours() % 12 || 12;
            },
            G: function(){
                return jsdate.getHours();
            },
            h: function(){
                return pad(f.g(), 2);
            },
            H: function(){
                return pad(jsdate.getHours(), 2);
            },
            i: function(){
                return pad(jsdate.getMinutes(), 2);
            },
            s: function(){
                return pad(jsdate.getSeconds(), 2);
            },
            //u not supported yet
            // Timezone
            //e not supported yet
            //I not supported yet
            O: function(){
                var t = pad(Math.abs(jsdate.getTimezoneOffset()/60*100), 4);
                if (jsdate.getTimezoneOffset() > 0) t = "-" + t; else t = "+" + t;
                return t;
            },
            P: function(){
                var O = f.O();
                return (O.substr(0, 3) + ":" + O.substr(3, 2));
            },
            //T not supported yet
            //Z not supported yet
            // Full Date/Time
            c: function(){
                return f.Y() + "-" + f.m() + "-" + f.d() + "T" + f.h() + ":" + f.i() + ":" + f.s() + f.P();
            },
            //r not supported yet
            U: function(){
                return Math.round(jsdate.getTime()/1000);
            }
        };
        return format.replace(/[\\]?([a-zA-Z])/g, function(t, s){
            if( t!=s ){
                // escaped
                ret = s;
            } else if( f[s] ){
                // a date function exists
                ret = f[s]();
            } else{
                // nothing special
                ret = s;
            }
            return ret;
        });
    }

</script>

{/block}